import React, { Component } from 'react';
import { WeaTop, WeaLocaleProvider, WeaTab, WeaNewScroll, WeaDialog, WeaBrowser, WeaRightMenu } from 'ecCom';
import { Button, message } from 'antd';
import { WeaTableNew } from 'comsMobx';
import { inject, observer } from 'mobx-react';
// import {toJS} from "mobx"

import SendFormComponent from './../components/SendFormComponent';

const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;

@inject('sendFormStore')
@inject('postDocManageStore')
@observer
class PostDocManage extends Component {
  constructor(props) {
    super(props);
    // this.browser = React.createRef();
    this.getButton = this.getButton.bind(this);
    this.getSearchForm = this.getSearchForm.bind(this);
  }

  componentDidMount() {
    const postDocManageStore = this.props.postDocManageStore;
    postDocManageStore.getTabFormData();
    postDocManageStore.getTableList();
    postDocManageStore.getInvalidForm();
  }

  componentWillUnmount() {
    const { postDocManageStore } = this.props;
    postDocManageStore.setSelectedRowKeys();
  }
  // WeaTop 的按钮
  getButton() {
    const postDocManageStore = this.props.postDocManageStore;
    let buttonArr = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lg7501@createPostDoc`} type="primary" onClick={postDocManageStore.openDialog}>{getLabel(387657, '新建发文')}</Button>,
    ];
    if (postDocManageStore.selectedKey != '4') {
      buttonArr.push(
        <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@1z8a56@selectUnit`}
          ref={''}
          title={getLabel(388123, '选择单位')}
          type="odocexchangecompany"
          customized={true}
          inputStyle={{ width: 200 }}
          onChange={unitIds => postDocManageStore.resendSubmit(unitIds)}
          isSingle={false}
        >
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@aa6v9s@resend`} type="primary" disabled={!(postDocManageStore.selectedRowKeys.length > 0)}>{getLabel(507765, '重新发送')}</Button>
        </WeaBrowser>,
      );
    }
    if (postDocManageStore.selectedKey == '0') {
      buttonArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9hxxbf@invalid`} type="primary" disabled={!(postDocManageStore.selectedRowKeys.length > 0)} onClick={postDocManageStore.showInvalidDialog}>{getLabel(15358, '作废')}</Button>);
    }
    return buttonArr;
  }
  // 获取右键菜单
  getRightMenu() {
    const { postDocManageStore } = this.props;
    const { openDialog, selectedKey, selectedRowKeys, showInvalidDialog, getTableList } = postDocManageStore;
    const disabled = !(selectedRowKeys.length > 0);
    const rightMenuDatas = [{
      key: '1',
      disabled: false,
      icon: <i className="icon-coms-search" />,
      content: getLabel('388113', '搜索'),
      onClick: () => getTableList(),
    }, {
      key: '2',
      disabled: false,
      icon: <i className="icon-coms-Add-to" />,
      content: getLabel('387657', '新建发文'),
      onClick: () => openDialog(),
    }];
    if (selectedKey == '0') {
      rightMenuDatas.push({
        key: '3',
        disabled,
        icon: <i className="icon-coms-delete" />,
        content: getLabel('15358', '作废'),
        onClick: () => showInvalidDialog(),
      });
    }

    return rightMenuDatas;
  }
  // 高级查询form表单的按钮
  getTabButtonsAd() {
    const postDocManageStore = this.props.postDocManageStore;
    return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3lge3r@search`} type="primary" onClick={() => postDocManageStore.getTableList()}>{getLabel(388113, '搜索')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7ogll5@reset`} type="ghost" onClick={() => this.resetForm()}>{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@t1i7ez@cancel`} type="ghost" onClick={() => { this.setShowSearchAd(postDocManageStore, false); }}>{getLabel(31129, '取消')}</Button>),
    ];
  }
  // 重置
  resetForm() {
    const { postDocManageStore } = this.props;
    postDocManageStore.selectedKey !== '0' && postDocManageStore.searchForm.resetForm();
    postDocManageStore.selectedKey === '0' && postDocManageStore.advancedSearchForm.resetForm();
  }
  // 获取高级搜索的form表单
  getSearchForm() {
    const { postDocManageStore } = this.props;
    return (
      <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@bcybja`} ref="scroll" height={'auto'} >
        {postDocManageStore.selectedKey !== '0' && postDocManageStore.searchForm.render({ needTigger: true }, {
          onEnterSearch: () => postDocManageStore.getTableList(),
        })}
        {postDocManageStore.selectedKey === '0' && postDocManageStore.advancedSearchForm.render({ needTigger: true }, {
          onEnterSearch: () => postDocManageStore.getTableList(),
        })}
      </WeaNewScroll>
    );
  }
  // 修改table列
  getColumns = (columns) => {
    const { postDocManageStore } = this.props;
    return columns.map((col) => {
      if (col.dataIndex == 'document_title') {
        return {
          ...col,
          title: col.title,
          className: '',
          render: (text, record) => (
            <a style={{ color: '#4d7ad8' }} onClick={() => { postDocManageStore.edit(record); }} >{text}</a>
          ),
        };
      }
      return col;
    });
  }

  // 高级搜索form表单的显隐
  setShowSearchAd(postDocManageStore, bool) {
    postDocManageStore.showSearchAd = bool;
  }
  // 获取收文和发文情况的按钮
  getDocInfoBtn() {
    const { newCreat, groupid, resendSubmit } = this.props.postDocManageStore;
    const { loading, uploadFile } = this.props.sendFormStore;
    let sendButton = [];
    if (newCreat) {
      sendButton.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5lmw31@send`} type="primary" onClick={() => this.onCheck()} disabled={loading || !uploadFile == true}>{getLabel(2083, '发送')}</Button>);
    } else if (groupid != 'Cancellation') {
      sendButton.push(
        <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@002wp8@selectUnit`}
          title={getLabel(388123, '选择单位')}
          type="odocexchangecompany"
          customized={true}
          inputStyle={{ width: 200 }}
          onChange={unitIds => resendSubmit(unitIds)}
          isSingle={false}
        >
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2edftb@resend`} type="primary">{getLabel(507765, '重新发送')}</Button>
        </WeaBrowser>,
      );
    } else {
      sendButton.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@v7o5be@nothing`} type="primary" style={{ display: 'none' }} />);
    }
    return sendButton;
  }
  // 查看收文情况弹窗按钮
  getDocInfoDialogBtn() {
    const { postDocManageStore } = this.props;
    const { resendSubmit, backout, unitArr } = this.props.postDocManageStore;
    const dialogButtons = [
      <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@rty514@selectUnit`}
        title={getLabel(388123, '选择单位')}
        type="odocexchangecompany"
        customized={true}
        inputStyle={{ width: 200 }}
        onChange={unitIds => resendSubmit(unitIds)}
        isSingle={false}
        onOpen={() => {
          postDocManageStore.unitArr = [];
          postDocManageStore.unitSelectedRowKeys = [];
        }}
      >
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sq6ni1@sendOther`} type="primary" className="resendOther">{getLabel(388098, '发送其他单位')}</Button>
      </WeaBrowser>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sw0hyo@repeal`} type="primary" disabled={!(unitArr.length > 0)} onClick={backout}>{getLabel(388099, '批量撤销')}</Button>,
    ];
    return dialogButtons;
  }
  // 获取拒收原因弹窗按钮
  getReasonDialogBtn() {
    const { hideReasonDialog, dialogType, backoutForm, invalidForm } = this.props.postDocManageStore;
    const reasonDialogButton = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@opa06a@cancel`} type="primary" onClick={hideReasonDialog}>{getLabel(31129, '取消')}</Button>,
    ];
    if (dialogType == 'backout') {
      reasonDialogButton.unshift(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@db7udw`} type="primary" onClick={() => this.reasonCheck('backout', backoutForm)}>{getLabel(23757, '撤销')}</Button>);
    } else if (dialogType == 'invalid') {
      reasonDialogButton.unshift(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vvrtqi`} type="primary" onClick={() => this.reasonCheck('invalid', invalidForm)}>{getLabel(15358, '作废')}</Button>);
    }
    return reasonDialogButton;
  }
  render() {
    const { postDocManageStore } = this.props;
    const { searchForm, advancedSearchForm, tableStore, reciveDocUnitTable, selectedKey, newCreat, groupid,
      dialogType, backoutForm, invalidForm, topTab, showSearchAd, selectedRowKeys, isShow, documentId, showRecive, showReasonDialog } = postDocManageStore;
    const { resendSubmit, backout, onOperatesClick, onRowSelect, closeDialog, closeReciveDialog, getReciveTableList, rerender,
      onUnitRowSelect, changeTab, getTableList, hideReasonDialog } = postDocManageStore;
    const searchsBaseValue = (selectedKey !== '0' && searchForm.getFormParams().Title) || (selectedKey === '0' && advancedSearchForm.getFormParams().Title);
    return (
      <div className="postDocManage">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@rj62o6`} datas={this.getRightMenu()}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@jz288k`}
            title={<span style={{ color: '#333333' }}>{getLabel(387595, '发文管理')}</span>}
            icon={<i className="icon-coms-fawen" />}
            iconBgcolor="#f93d3d"
            buttons={this.getButton()}
          >
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@zvdhvc`}
              datas={topTab}
              keyParam="viewcondition" // 主键
              countParam="groupid"
              selectedKey={selectedKey}
              onChange={v => changeTab(v)}
              searchType={['base', 'advanced']}
              searchsBaseValue={searchsBaseValue}
              onSearchChange={(v) => {
                if (postDocManageStore.selectedKey !== '0') {
                  searchForm.updateFields({ Title: { value: v } }, false);
                } else {
                  advancedSearchForm.updateFields({ Title: { value: v } }, false);
                }
              }}
              showSearchAd={showSearchAd}
              setShowSearchAd={bool => this.setShowSearchAd(postDocManageStore, bool)}
              buttonsAd={this.getTabButtonsAd()}
              searchsAd={this.getSearchForm()}
              onSearch={(text) => { getTableList(text); }}
              advanceHeight={120}
              onOperatesClick={(record, index, operate, flag) => onOperatesClick(record, index, operate, flag, this.refs.browser)}
            />
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@1eck2w`}
              needScroll={true}
              comsWeaTableStore={tableStore}
              getColumns={this.getColumns}
              rowSelection={{
                selectedRowKeys,
                onChange: onRowSelect,
              }}
              onOperatesClick={(record, index, operate, flag) => onOperatesClick(record, index, operate, flag, this.refs.browser)}
            />
          </WeaTop>
        </WeaRightMenu>

        {/* 新建和查看发文弹窗 */}
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@q4cqt2`}
          className="newPostDocDialog"
          title={(newCreat === true && getLabel(387657, '新建发文')) || (newCreat === false && getLabel(388127, '查看发文'))}
          icon="icon-coms-official"
          visible={isShow}
          buttons={this.getDocInfoBtn()}
          onCancel={closeDialog}
          draggable={true}
          maskClosable={true}
          style={{ width: 800, height: 570 }}
        >
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@gpc5qy`} ref="scroll" className="newPostDocDialogForm" width={750} height={570}>
            <SendFormComponent ecId={`${this && this.props && this.props.ecId || ''}_SendFormComponent@dhaifw`} id={documentId} groupid={groupid} />
          </WeaNewScroll>
        </WeaDialog>

        {/* 收文单位信息弹窗 */}
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@7v85zo`}
          className="newPostDocDialog"
          title={getLabel(388097, '收文单位信息')}
          iconBgcolor="#f14a2d"
          icon={'icon-coms-official'}
          visible={showRecive}
          buttons={this.getDocInfoDialogBtn()}
          onCancel={closeReciveDialog}
          draggable={true}
          maskClosable={true}
          style={{ width: 750, height: 570 }}
        >
          <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@aryclt`}
            searchType={['base']}
            onSearch={getReciveTableList}
          />
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@affc8a`}
            comsWeaTableStore={reciveDocUnitTable}
            rowSelection={{
              selectedRowKeys,
              onChange: onUnitRowSelect,
            }}
            onOperatesClick={backout}
          />
        </WeaDialog>

        {/* 撤销公文和作废公文弹窗 */}
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@jwcbt6`}
          title={dialogType == 'backout' && getLabel(388128, '撤销公文') || dialogType == 'invalid' && getLabel(388129, '作废公文')}
          onCancel={() => hideReasonDialog()}
          visible={showReasonDialog}
          style={{ width: 750, height: '212px' }}
          // maskClosable={true}
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          buttons={this.getReasonDialogBtn()}
          className="recDocManage_rejectReason"
          key={rerender}// 用来重新渲染组件
        >
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@gj85se`} ref="scroll" className="rejectReason">
            {dialogType == 'backout' && backoutForm.render({ needTigger: false })}
            {dialogType == 'invalid' && invalidForm.render({ needTigger: false })}
          </WeaNewScroll>
        </WeaDialog>
        {/* 单位浏览按钮弹窗 */}
        <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@cz0gc8`}
          ref="browser"
          title={getLabel(388123, '选择单位')}
          type="odocexchangecompany"
          inputStyle={{ display: 'none' }}
          onChange={unitIds => resendSubmit(unitIds)}
          isSingle={false}
          onClose={() => {
            postDocManageStore.selectedRowKeys = [];
          }}
        />
      </div>
    );
  }
  // 文件上传校验
  onCheck() {
    const { form, uploadFile } = this.props.sendFormStore;
    form.validateForm().then((data) => {
      if (data.isValid && uploadFile) {
        this.saveSendForm();
      } else if (uploadFile) {
        data.showErrors();
      } else {
        message.error(getLabel('388233', '正文没有上传'));
      }
    });
  }
  // 拒收校验
  reasonCheck(type, form) {
    const { postDocManageStore } = this.props;
    form.validateForm().then((data) => {
      if (data.isValid) {
        if (type == 'backout') {
          postDocManageStore.backoutSubmit();
        } else {
          postDocManageStore.invalidSubmit();
        }
      } else {
        data.showErrors();
      }
    });
  }

  saveSendForm() {
    const { postDocManageStore, sendFormStore } = this.props;
    sendFormStore.loading = true;
    sendFormStore.saveSendForm(postDocManageStore.closeDialog, postDocManageStore.getTableList);
  }
}
export default PostDocManage;
